
layui.use(['form', 'layer', 'table', 'laydate'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var storestaff_url = $('.storestaff_url').val();
    var save_url = $('.save_url').val();


    function init_laydate(){
        var laydate = layui.laydate;
        // 执行一个laydate实例
        laydate.render({
            elem: '.start_date', //指定元素
            type: 'date',
            //type: 'datetime',
            format: 'yyyy年MM月dd日',
            trigger: 'click',
            //max : 0,
            //mark : {"0-12-15":"生日"},
            done: function(value, date){

            }
        });

        laydate.render({
            elem: '.end_date'
        });
    }

    if($('#map_container').length > 0){
        // 百度地图API功能
        //创建Map实例
        var map = new BMap.Map("map_container");
        //初始化武汉坐标
        var point = new BMap.Point(114.405492,30.502934);
        var offsetY = 200;
        //地图平移缩放控件：默认左上方
        map.addControl(new BMap.NavigationControl());
        //比例尺控件，默认位于地图左下方，显示地图的比例关系
        map.addControl(new BMap.ScaleControl());
        map.centerAndZoom(point,12);
        //添加鼠标滚动缩放
        map.enableScrollWheelZoom(true);
        //设置标注的图标

        //显示地址信息窗口
        var marker = new BMap.Marker(point);
        //把标注添加到地图上
        map.addOverlay(marker);

        //地址解析类
        var gc = new BMap.Geocoder();
        function showLocationInfo(pt, rs){
            var addComp = rs.addressComponents;
            $("#longitude").val(pt.lng);
            $("#latitude").val(pt.lat);
            console.log('经纬度：'+pt.lat+' '+pt.lng);
            $("#address_geo").val(pt.lat+','+pt.lng);
        }

        //删除标注
        function deletePoint(){
            var allOverlay = map.getOverlays();
            for (var i = 0; i < allOverlay.length; i++){
                map.removeOverlay(allOverlay[i]);
            }
        }

        //根据选择框或输入框获取地址
        var _area = {
            //keyword: '',
            _address: $("#address"),
            unChecked:function(val){
                return (val==''||typeof (val)=='undefined'||val==null|| val=='省份'||val=='地级市'||val=='市、县级市')?false:true;
            },
            list: function(){
                var _joinArea = '';
                if(_area.unChecked(this._address.val())){
                    //_joinArea = this._address.val();
                    //_joinArea += ' ' + this._address.val();
                    _joinArea += ' ' + $('select[name=region]').find('option:selected').text() + this._address.val();
                    //console.log(_joinArea);
                }

                return _joinArea;
            },
            init: function(){
                //绑定百度地图
                var _this=_area.list();
                //定义local
                var local = new BMap.LocalSearch(map, {
                    renderOptions: {
                        map: map,
                        panel: "results",//结果容器id
                        autoViewport: true,   //自动结果标注
                        selectFirstResult: true  , //指定到第一个目标
                        enableRouteSearchBox: true,
                        enableRouteInfo:true
                    },
                    pageCapacity: 1
                });

                local.setSearchCompleteCallback(function (searchResult) {
                    //console.log(searchResult);
                    if(searchResult){
                        var poi = searchResult.getPoi(0);
                        //console.log(poi);
                        //document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat;
                        if(poi){
                            map.centerAndZoom(poi.point, 12);
                            gc.getLocation(poi.point, function(rs){
                                showLocationInfo(poi.point, rs);
                            });
                        }
                    }
                });
                local.search(_this);
            }
        };

        //全局变量：存储address字符串长度做判断
        var _thisLength='';
        $("#address").keydown(function(){
            _thisLength=$(this).val().length;
        });
        $("#address").keyup(function(){
            var _newLength=$(this).val().length;
            var timer=setTimeout(function(){
                if(_thisLength<=_newLength){
                    deletePoint();
                    _area.init();
                }else{
                    clearTimeout(timer);
                }
            },1000);
        });
        $("#address").blur(function(){
            deletePoint();
            _area.init();
        });

        // 初始化
        if($("#address").val() != ""){
            $("#address").blur();
        }
    }

    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        cols : [[
            {field: 'name', title: '门店名称', align:'center'},
            {field: 'store_type', title: '门店类型', align:'center', templet:function(data){
                if (data.store_type == 1) {
                    return '<span class="layui-btn layui-btn-normal layui-btn-xs">自营店</span>'
                } else {
                    return '<span class="layui-btn layui-btn-normal layui-btn-xs">加盟店</span>'
                }
            }},
            {field: 'region', title: '所在城市', align:'center'},
            {field: 'address', title: '门店地址', align:'left'},
            {field: 'person', title: '联系人', align:'center'},
            {field: 'phone', title: '手机号', align:'center'},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                //html += '<a class="layui-btn layui-btn-xs layui-bg-black" href="'+storestaff_url+'?store_id='+data.id+'">员工</a>';

                return html;
            }}
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function(){
        var name = $('.searchBox').find('input[name=name]').val();
        var store_type = $('.searchBox').find('select[name=store_type]').val();
        if(name != '' || store_type != ''){
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: name,
                    store_type: store_type,
                }
            });
        }else{
            layer.msg("请选择筛选条件");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function(){
        table.reload("tableList", {
            where: {
                name: '',
                store_type: ''
            }
        });
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // 删除
    /*$('.del-btn').on('click', function(){
        layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
            $.ajax({
                url: delete_url,
                data: {"id": data.id},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        layer.msg('已删除', {icon: 1, time: 1000});
                        tableIns.reload();
                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
        });
    });*/

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: -1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.1
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '650px'
            , top: 0
            , content: content
            , success: function () {
                //init_laydate(); // 不生效
            }
        });
    }

    // 批量导出
    $('#export_csv').on('click', function(){
        var url = $(this).data('url');
        var name = $('.searchBox').find('input[name=name]').val();

        var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
        $form += '<input name="name" value="'+name+'" >';
        $form += '</form>';
        if($(document).find('#export_form').length){
            $(document).find('#export_form').remove();
        }
        $(document.body).append($form);
        // 提交表单，实现下载
        $(document).find('#export_form').submit();
    });

    // 自定义验证规则
    form.verify({
        name: function(value){
            if(value == ''){
                return '门店名不能为空';
            }
            if(value.length > 40){
                return '门店名最多为40个字符';
            }
        },
        address_geo: function(value){
            if(value == ''){
                return '该地址不是有效地址';
            }
        },
        phone: function(value){
            if(value == ''){
                return '手机号不能为空';
            }
            if(!/^1(3|4|5|6|7|8|9)[0-9]\d{8}$/.test(value)){
                return '手机号格式不正确';
            }
        },
    });

    // 表单提交
    form.on("submit(laySave)", function(data){
        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        if(data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    layer.closeAll("iframe");
                    parent.layui.table.reload('tableList', {});
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    })

});